package IOTWeb.com.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import IOTWeb.com.IOTMain;
import IOTWeb.com.dao.ExcepContent;
import IOTWeb.com.dao.meth.ExcepContentMeth;
import IOTWeb.com.utils.FileOption;
import IOTWeb.com.utils.H2ConnectionPool;
import IOTWeb.com.utils.HttpRequestFormOtherResolver;
import IOTWeb.com.utils.Utils;

public class ExcepContentHandler implements HttpHandler {

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		new Thread(new Runnable() {
			@Override
            public void run() {
				try {	
		            System.out.println("url: " + exchange.getRequestURI().toString());
		            ExcepContentMeth excepContentMeth = new ExcepContentMeth();
		            ExcepContent excepContent = new ExcepContent();
					Utils utils = new Utils();
		    		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		    		java.sql.Date sDate = null;
		    		String result = "";
					Headers headers = exchange.getRequestHeaders();
					List<String> tocken = headers.get("token");
					if(tocken != null && !tocken.isEmpty() && utils.haveTocken(tocken)) {
						if (exchange.getRequestURI().toString().equals("/excepcontent/insert")) {
			                int length = Integer.parseInt(headers.getFirst("Content-length"));
			                InputStream in = exchange.getRequestBody();
			                byte[] body;
			        		H2ConnectionPool h2 = new H2ConnectionPool();
							body = IOUtils.toByteArray(in, length);
							String add = null;
			                List<HttpRequestFormOtherResolver.ParamItem> params = HttpRequestFormOtherResolver.resolveForm(headers, body);
			                for (HttpRequestFormOtherResolver.ParamItem paramItem : params) {
		                        System.out.println(paramItem.getName()+":"+paramItem.getVal());
		                        if(paramItem.getName().equals("type"))
		                        	excepContent.setType(paramItem.getVal());
		                        else if(paramItem.getName().equals("violator"))
		                        	excepContent.setViolator(paramItem.getVal());
		                        else if(paramItem.getName().equals("checkor"))
		                        	excepContent.setCheckor(paramItem.getVal());
		                        else if(paramItem.getName().equals("description"))
		                        	excepContent.setDescription(paramItem.getVal());
		                        else if(paramItem.getName().equals("file_id"))
		                        	excepContent.setFile_id(paramItem.getVal());
		                        else if(paramItem.getName().equals("record_time")) {
		                			java.util.Date date3 = sdf2.parse(paramItem.getVal());
		                			sDate = new java.sql.Date(date3.getTime());
		                			excepContent.setRecord_time(sDate);
		                        }
			                }
			                excepContentMeth.insertExcep(excepContent);
							exchange.sendResponseHeaders(200, "success".length());
			                OutputStream out = exchange.getResponseBody();
			                in.close();
			                out.write("success".getBytes());
			                out.flush();
			                out.close();
						}else {
							Headers responseHeaders = exchange.getResponseHeaders();
							utils.setResponseJson(responseHeaders);
							OutputStream os = exchange.getResponseBody();
							PrintStream out = new PrintStream(os);
							if (exchange.getRequestURI().toString().equals("/excepcontent/select")) {
								result = excepContentMeth.selectExcep();
							}else if(exchange.getRequestURI().toString().substring(0, 20).equals("/excepcontent/delete")){
								String queryString = exchange.getRequestURI().getQuery();//get:获得url后面的值
								Map<String, String> queryStringInfo = utils.formData2Dic(queryString);
								Integer id = Integer.valueOf(queryStringInfo.get("id"));
								excepContentMeth.deletExcep(id);
								result = "成功删除id为"+id+"的信息";
							}else
								result = "404!!!接口错误";
							byte[] bytes = result.getBytes("utf-8");
							int len = bytes.length;
							exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, len);
							out.write(bytes, 0, bytes.length);
							out.flush();
							out.close();
						}
					}else {
						utils.tockenError(exchange);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
}
